import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;

/**
 * Created by huangxiaolu on 2015/2/13.
 */
public class Worker {
    public static void main(String[] args)
            throws IOException, InterruptedException {
        subscribe();
    }

    private static void recieve() throws IOException, InterruptedException {
        String exchangeName = "hello";
        ConnectionFactory factory1 = new ConnectionFactory();
        factory1.setHost("localhost");
        Connection connection1 = factory1.newConnection();
        Channel channel1 = connection1.createChannel();
        channel1.exchangeDeclare(exchangeName, "fanout");
        String queueName = channel1.queueDeclare().getQueue();
        channel1.queueBind(queueName, exchangeName, "");
        QueueingConsumer consumer = new QueueingConsumer(channel1);
        channel1.basicConsume(queueName, false, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            byte[] body = delivery.getBody();
            String msg = new String(body);
            channel1.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            System.out.println(msg);
        }
    }

    private static void subscribe() throws IOException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String exchangeName = "logs-routed";
        String queueName = channel.queueDeclare().getQueue();
        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueBind(queueName, exchangeName, "info");
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, false, consumer);
        System.out.println("[*] waiting for message");
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            int index = message.indexOf(":");
            String msg = message.substring(0, index);
            double length = 2 * message.length() / (1024 * 1024);
            System.out.format("[x] %s: %s Mb%n", msg, length);
        }
    }

}
